package com.zycfc.zsf.boot.redis;

import com.zycfc.zsf.boot.serializer.*;
import org.springframework.data.redis.connection.jedis.*;
import com.zycfc.zsf.boot.core.common.*;
import org.springframework.data.redis.connection.*;
import com.zycfc.zsf.boot.redis.command.*;
import redis.clients.jedis.*;
import com.zycfc.zsf.boot.redis.autoconfigure.*;
import org.slf4j.*;

public class RedisOperaterFactory
{
    private static final Logger logger;
    
    public static IRedisOperater create(final RedisProperties config, final ISerializer redisISerializer, final RedisConnectionFactory connectionFactory, final String appName, final String profilesActive) {
        if (null == connectionFactory) {
            return null;
        }
        if (!(connectionFactory instanceof JedisConnectionFactory)) {
            RedisOperaterFactory.logger.debug("connectionFactory is not JedisConnectionFactory");
            return null;
        }
        RedisConnection redisConnection = null;
        try {
            redisConnection = connectionFactory.getConnection();
        }
        catch (Throwable e) {
            RedisOperaterFactory.logger.error(e.getMessage(), e);
        }
        RedisBinaryCommand redisBinaryCommand = null;
        if (null != redisConnection) {
            if (redisConnection instanceof JedisClusterConnection) {
                final JedisClusterConnection redisClusterConnection = (JedisClusterConnection)redisConnection;
                final JedisCluster jedisCluster = redisClusterConnection.getNativeConnection();
                if (null != jedisCluster) {
                    redisBinaryCommand = new JedisClusterBinaryCommand(jedisCluster);
                    RedisOperaterFactory.logger.debug("IRedisOperater with JedisClusterBinaryCommand");
                }
            }
            else if (redisConnection instanceof JedisConnection) {
                redisBinaryCommand = new JedisBinaryCommand((JedisConnectionFactory)connectionFactory);
                RedisOperaterFactory.logger.debug("IRedisOperater with RedisOperater");
            }
            final boolean notProdEnv = !EnvNameEnum.prod.name().equals(profilesActive);
            return new RedisOperater(config, redisISerializer, redisBinaryCommand, appName, notProdEnv);
        }
        return null;
    }
    
    static {
        logger = LoggerFactory.getLogger((Class)RedisOperaterAutoConfigure.class);
    }
}
